const getToken = function () {
    return wx.getStorageSync("token");
}

const createOption = function (option, successed, failed, completed) {
    if (!!successed) {
        option.success = (res) => {
            const pojo = res.data
            if (!!pojo.code && pojo.code === 200) {
                successed(pojo)
            } else if (!!failed) {
                failed(pojo)
            }
        }
    }
    if (!!failed) {
        option.fail = (err) => {
            failed({
                code: err.errno,
                msg: err.errMsg
            })
        }
    }
    if (!!completed) {
        option.complete = (res) => {
            completed(res)
        }
    }
    return option;
}

const getJSON = function (path, successed, failed, completed) {
    wx.request(createOption({
        url: path,
        method: 'GET',
    }, successed, failed, completed))
}

const getJSONWithToken = function (path, successed, failed, completed) {
    const token = getToken()
    wx.request(createOption({
        url: path,
        method: 'GET',
        header: {
            Authorization: token
        }
    }, successed, failed, completed));
}

const postJSON = function (path, params, successed, failed, completed) {
    wx.request(createOption({
        url: path,
        data: params,
        method: 'POST',
    }, successed, failed, completed))
}

const postJSONWithToken = function (path, params, successed, failed, completed) {
    const token = getToken()
    wx.request(createOption({
        url: path,
        data: params,
        method: 'POST',
        header: {
            Authorization: token
        }
    }, successed, failed, completed));
}

const putJSONWithToken = function (path, params, successed, failed, completed) {
    const token = getToken()
    wx.request(createOption({
        url: path,
        data: params,
        method: 'PUT',
        header: {
            Authorization: token
        }
    }, successed, failed, completed));
}

const uploadFile = function (path, filePath, successed, failed, completed) {
    wx.uploadFile(createOption({
        url: path,
        filePath: filePath,
        name: 'file',
    }, successed, failed, completed))
}

module.exports = {
    getJSON,
    getJSONWithToken,
    postJSON,
    postJSONWithToken,
    putJSONWithToken,
    uploadFile,
}